﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreData;
using EntityData;
using Helper;
using System.Data;
namespace Services
{

    public partial class Receipt_VoucherFeeService
    {
       readonly IReceipt_VoucherFeeEntity entity;
       readonly IStudent_FeeEntity StudentFeeEntity;
       readonly IStudentEntity StudentEntity;
      // readonly CourseService CourseEntity;
       readonly IStudent_FeeTimeEntity StudentFeeTimeEntity;
       public Receipt_VoucherFeeService()
       {
           this.entity = new Receipt_VoucherFeeEntity();
           StudentFeeEntity = new Student_FeeEntity();
           StudentEntity = new StudentEntity();
           StudentFeeTimeEntity = new Student_FeeTimeEntity();
         //  CourseEntity = new CourseService();

       }

       #region Main Method

       /// <summary>
       /// Save 
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public long Save(object _model)
       {
           try
           {
               var obj = (CoreData.Receipt_VoucherFee)_model;
               var id = obj.ID;
               if (id == 0)
               {
                   id = entity.Save(obj, Table.Receipt_VoucherFee.ToString());
               }
               else
               {
                   id = entity.Update(obj, Table.Receipt_VoucherFee.ToString());
               }
               if (obj.Type ==0)
               {
                   //bat dau kiem tra va insert vao bang theo doi học phi (studentfee)
                   Student_Fee stfee = new Student_Fee();
                   try
                   {
                       stfee = StudentFeeEntity.GetBySearchString(" Student_Fee.StudentID=" + obj.StudentID, Table.Student_Fee.ToString()).FirstOrDefault();
                       if (stfee == null)
                       {
                           stfee = new Student_Fee();
                       }
                   }
                   catch
                   {
                   }

                   //lay tat ca phieu thu cua hoc vien dang xu ly hien hanh tính tổng lại số học phí đã đóng
                   var allreceipt = GetList(" Receipt_VoucherFee.StudentID=" + obj.StudentID);
                   //lay thong tin hoc vien va thong tin khoa hoc
                   var student = StudentEntity.GetById(obj.StudentID, Table.Student.ToString());
                   long totalmoney = 0;
                   foreach (var item in allreceipt)
                   {
                       totalmoney += item.Money;
                   }
                   //sau đo cập nhât lại bảng theo dõi học phí

                   stfee.Money = totalmoney;

                   if (stfee.Money >= student.TotalFee)
                   {
                       stfee.Status = 0;

                   }
                   else
                   {
                       stfee.Status = 1;
                   }

                   stfee.StudentID = obj.StudentID;
                   // stfee.Type = student.TypeOfFee;
                   if (stfee.ID == 0)
                   {
                       StudentFeeEntity.Save(stfee, Table.Student_Fee.ToString());
                   }
                   else
                   {
                       StudentFeeEntity.Update(stfee, Table.Student_Fee.ToString());
                   }
               }
               return id;
           }
           catch { return -1; }
       }

       /// <summary>
       /// Get by ID
       /// </summary>
       /// <param name="_id"></param>
       /// <returns></returns>
       public CoreData.Receipt_VoucherFee GetByID(long _id)
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetReceiptFeeVoucher, " Receipt_VoucherFee.ID=" + _id)).FirstOrDefault();
           }
           catch { return null; }
       }

       /// <summary>
       /// Get List
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.Receipt_VoucherFee> GetList()
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetReceiptFeeVoucher, "1=1")).ToList();
           }
           catch { return null; }

       }

       /// <summary>
       /// Get List with Linq
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.Receipt_VoucherFee> GetListByLINQ(Func<CoreData.Receipt_VoucherFee, Boolean> _where)
       {
           try
           {
               return entity.GetMany(_where, Table.Receipt_VoucherFee.ToString()).ToList();
           }
           catch { return null; }
       }
       /// <summary>
       /// Get One with Linq
       /// </summary>
       /// <returns></returns>
       public CoreData.Receipt_VoucherFee GetOneByLINQ(Func<CoreData.Receipt_VoucherFee, Boolean> _where)
       {
           try
           {
               return entity.Get(_where, Table.Receipt_VoucherFee.ToString());
           }
           catch { return null; }
       }

       /// <summary>
       /// Get List with search string
       /// </summary>
       /// <returns></returns>
       public IList<CoreData.Receipt_VoucherFee> GetList(string _searchstring)
       {
           //search theo tieu chi nao do         
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetReceiptFeeVoucher,"Receipt_VoucherFee.Type=0 and "+_searchstring)).ToList();
           }
           catch { return null; }
       }


       /// <summary>
       /// Delete
       /// </summary>
       /// <param name="_model"></param>
       /// <returns></returns>
       public bool Delete(object _model)
       {
           try
           {
               Receipt_VoucherFee obj = (Receipt_VoucherFee)_model;
               entity.Delete(obj, Table.Receipt_VoucherFee.ToString());
               Student_Fee student_fee = StudentFeeEntity.GetBySearchString(" StudentID=" + obj.StudentID, Table.Student_Fee.ToString()).FirstOrDefault();
               if (student_fee != null)
               {
                   if (student_fee.Money > 0)
                   {
                       student_fee.Money -= obj.Money;
                       if (student_fee.Money < 0)
                       {
                           student_fee.Money = 0;
                       }
                       StudentFeeEntity.Update(student_fee, Table.Student_Fee.ToString());
                   }
               }
               return true;
           }
           catch { return false; }
       }


       #endregion



        #region Other Method



       public Receipt_VoucherFee GetByVoucherID(long voucherid)
       {
           try {
               return entity.GetBySearchString("  VoucherID=" + voucherid, Table.Receipt_VoucherFee.ToString()).ToList()[0];
           }
           catch { return null; }
       }
        /// <summary>
        /// Sử dụng để lấy phieu thu là đóng phí bảo lưu
        /// </summary>
        /// <param name="StudentID"></param>
        /// <param name="type"></param>
        /// <returns></returns>
       public Receipt_VoucherFee GetByVoucherFeeSave(long StudentID)
       {
           try
           {
               return entity.GetByCusTomSQL(String.Format(SQLCommand.GetStudentFeeSave, " Receipt_VoucherFee.Type=1 and Receipt_VoucherFee.StudentID=" + StudentID )).ToList()[0];
           }
           catch { return null; }
       }

       public IList<Receipt_VoucherFee> GetByStudentID(long studentid)
       {
           try
           {
               return entity.GetBySearchString(" Receipt_VoucherFee.Type=0 and Receipt_VoucherFee.StudentID=" + studentid, Table.Receipt_VoucherFee.ToString()).ToList();
           }
           catch { return null; }
       }



       public string CalMoneyDebt(long studentID, string type)
       {
           try
           {
               var data = StudentEntity.GetById(studentID, Table.Student.ToString());
               var listvoucher = GetByStudentID(studentID);

               return CalMoneyDebt(data, listvoucher,type, data.TypeOfFee);
           }
           catch { return Helper.StringHelper.FormatVND(0); }
       }

       string CalMoneyDebt(Student data, IList<Receipt_VoucherFee> listvoucher, string typestring, int type)
       {
           string result = "";
           if (listvoucher == null || listvoucher.Count <= 0)
               result = Helper.StringHelper.FormatVND(0);
           var subvoucher = listvoucher.Where(c => c.TimeFee.Contains(typestring));
           long t = 0;
           if (type==1)
           {
               data.TotalFee = data.TotalFee;
           }
           if (type==2)
           {
               data.TotalFee = data.TotalFee / 2;
           }
           if (type==3)
           {
               data.TotalFee = data.TotalFee / 3;
           }
           if (type==4)
           {
               data.TotalFee = data.TotalFee / 4;
           }
           if (type==6)
           {
               data.TotalFee = data.TotalFee / 6;
           }
           foreach (var item in subvoucher)
           {
               t += item.Money;
           }
           if (t < data.TotalFee)
           {
               result = Helper.StringHelper.FormatVND(data.TotalFee - t);
           }
           else
           {
               result = Helper.StringHelper.FormatVND(0);
           }
           return result;
       }


       #region Over Pay Info
       /// <summary>
        /// Lấy danh sách phiếu thu mà học viên đóng dư
        /// </summary>
        /// <returns></returns>
       public IList<OverPayInfo> GetListStudentPayOverBalance()
       {
           IList<OverPayInfo> datas = new List<OverPayInfo>();
           var feetopay = StudentFeeTimeEntity.GetByCusTomSQLReturnDatatable(@"select Student_FeeTime.* from
                          Student_FeeTime inner join Student on Student_FeeTime.StudentID = Student.ID
                           where Student.Status <> 2 and Student.Status <> 10"); //lấy tổng học phí mà học viên buộc phải đóng
           if (feetopay != null && feetopay.Rows.Count!=0)
           {
               foreach (DataRow item in feetopay.Rows)
               {
                   var receiptvoucher = GetByStudentID((long)item["StudentID"]);
                   if (receiptvoucher != null && receiptvoucher.Count !=0)
                   {
                       var student = StudentEntity.GetById((long)item["StudentID"], Table.Student.ToString());
                       AddOverPayInfo(datas, item, receiptvoucher,"Lần 1", student);
                       AddOverPayInfo(datas, item, receiptvoucher, "Lần 2", student);
                       AddOverPayInfo(datas, item, receiptvoucher, "Lần 3", student);
                       AddOverPayInfo(datas, item, receiptvoucher, "Lần 4", student);
                       AddOverPayInfo(datas, item, receiptvoucher, "Lần 5", student);
                       AddOverPayInfo(datas, item, receiptvoucher, "Lần 6", student);
                   }
               }
           }
           return datas;
          
       }

       private void AddOverPayInfo(IList<OverPayInfo> datas, DataRow item, 
           IList<Receipt_VoucherFee> receiptvoucher, string feeTime, Student student)
       {
           var fee = receiptvoucher.Where(c => c.TimeFee.Contains(feeTime));
           var feePaid = fee.Sum(c => c.Money);
           String voucherCode = string.Empty;
           if (fee != null && fee.Count() != 0)
           {

               var voucher = GetList("Voucher.ID =" + fee.LastOrDefault().VoucherID);
                if (voucher != null && voucher.Count != 0)
                {
                    voucherCode += voucher.FirstOrDefault().ReceiptVoucherCodeExt;
                }
               
           }
           switch(feeTime)
           {
               case "Lần 1":
                   if (fee != null && (int)item["Money1"] < fee.Sum(c => c.Money))
                   {
                       OverPayInfo overPayInfo = new OverPayInfo
                       {
                           FeeTime = feeTime,
                           Money = (int)item["Money1"],
                           MoneyPaid = feePaid,
                           MoneyOver = feePaid - (int)item["Money1"],
                           StudentName =student.Name,
                           ReceiptVoucherFee = voucherCode
                       };
                       datas.Add(overPayInfo);
                   }
                 break;
               case "Lần 2":
                 if (fee != null && (int)item["Money2"] < fee.Sum(c => c.Money))
                 {
                     OverPayInfo overPayInfo = new OverPayInfo
                     {
                         FeeTime = feeTime,
                         Money = (int)item["Money2"],
                         MoneyPaid = feePaid,
                         MoneyOver = feePaid - (int)item["Money2"],
                         StudentName = student.Name,
                         ReceiptVoucherFee = voucherCode
                     };
                     datas.Add(overPayInfo);
                 }
                 break;
               case "Lần 3":
                 if (fee != null && (int)item["Money3"] < fee.Sum(c => c.Money))
                 {
                     OverPayInfo overPayInfo = new OverPayInfo
                     {
                         FeeTime = feeTime,
                         Money = (int)item["Money3"],
                         MoneyPaid = feePaid,
                         MoneyOver = feePaid - (int)item["Money3"],
                         StudentName = student.Name,
                         ReceiptVoucherFee = voucherCode
                     };
                     datas.Add(overPayInfo);
                 }
                 break;
               case "Lần 4":
                 if (fee != null && (int)item["Money4"] < fee.Sum(c => c.Money))
                 {
                     OverPayInfo overPayInfo = new OverPayInfo
                     {
                         FeeTime = feeTime,
                         Money = (int)item["Money4"],
                         MoneyPaid = feePaid,
                         MoneyOver = feePaid - (int)item["Money4"],
                         StudentName = student.Name,
                         ReceiptVoucherFee = voucherCode
                     };
                     datas.Add(overPayInfo);
                 }
                 break;
               case "Lần 5":
                 if (fee != null && (int)item["Money5"] < fee.Sum(c => c.Money))
                 {
                     OverPayInfo overPayInfo = new OverPayInfo
                     {
                         FeeTime = feeTime,
                         Money = (int)item["Money5"],
                         MoneyPaid = feePaid,
                         MoneyOver = feePaid - (int)item["Money5"],
                         StudentName = student.Name,
                         ReceiptVoucherFee = voucherCode
                     };
                     datas.Add(overPayInfo);
                 }
                 break;
               case "Lần 6":
                 if (fee != null && (int)item["Money6"] < fee.Sum(c => c.Money))
                 {
                     OverPayInfo overPayInfo = new OverPayInfo
                     {
                         FeeTime = feeTime,
                         Money = (int)item["Money6"],
                         MoneyPaid = feePaid,
                         MoneyOver = feePaid - (int)item["Money6"],
                         StudentName = student.Name,
                         ReceiptVoucherFee = voucherCode
                     };
                     datas.Add(overPayInfo);
                 }
                 break;
          }
       }
       #endregion

        #endregion

    }
         
}
